package com.arethusa;

import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import simpleorm.core.SConnection;
import simpleorm.core.SPreparedStatement;
import simpleorm.core.SResultSet;
import simpleorm.core.SValidationException;

import com.arethusa.langebaandb.*;
import com.ibm.j2x.swing.util.TableUtilities;
import com.ibm.j2x.util.CollectionUtilities;
import java.awt.Insets;

public class OnderhoudCategorie extends JPanel {

	static final long serialVersionUID=1;
	private JPanel invoerPanel = null;
	private JScrollPane jScrollPane = null;
	private JTable jTable = null;
	private JButton invoerButton = null;
	private JButton wijzigButton = null;
	private JButton verwijderButton = null;
	private List<CategorieBean> olist;
	private String sortBy = "cat";
	private Boolean sortAscending = new Boolean(true);
	private JButton herstelButton = null;
	private JLabel jLabel = null;
	private JTextField categorieTextField = null;
	private JLabel jLabel1 = null;
	private JComboBox sexComboBox = null;
	private JLabel jLabel2 = null;
	private JTextField vanTextField = null;
	private JLabel jLabel3 = null;
	private JTextField temTextField = null;
	
	private class InvoerButtonActionListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			CategorieBean cur = new CategorieBean();
			cur.setCat(categorieTextField.getText());
			cur.setSex((String)sexComboBox.getSelectedItem());
			try {
				cur.setVan(new Integer(vanTextField.getText()));
				cur.setTem(new Integer(temTextField.getText()));
				cur.create();
				fillTable(sortBy, sortAscending);
				clearInvoer();
			} catch (SValidationException e1) {
				JOptionPane.showMessageDialog(null,
					e1.getMessage(),
					"Validatie", JOptionPane.ERROR_MESSAGE);
			} catch (NumberFormatException e2) {
				JOptionPane.showMessageDialog(null,
					"Leeftijd moet een nummer zijn.",
					"Validatie", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private class WijzigButtonActionListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			CategorieBean cur = new CategorieBean();
			cur.setCat(categorieTextField.getText());
			cur.setSex((String)sexComboBox.getSelectedItem());
//			System.out.println((String)sexComboBox.getSelectedItem());
			try {
				cur.setVan(new Integer(vanTextField.getText()));
				cur.setTem(new Integer(temTextField.getText()));
				cur.update();
				fillTable(sortBy, sortAscending);
				clearInvoer();
			} catch (SValidationException e1) {
				JOptionPane.showMessageDialog(null,
					e1.getMessage(),
					"Validatie", JOptionPane.ERROR_MESSAGE);
			} catch (NumberFormatException e2) {
				JOptionPane.showMessageDialog(null,
					"Leeftijd moet een nummer zijn.",
					"Validatie", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private class VerwijderButtonActionListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			if(JOptionPane.showConfirmDialog(null,
					"Zeker weten?","Verwijderen",
					JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_CANCEL_OPTION ) return;
			CategorieBean cur = new CategorieBean();
			cur.setCat(categorieTextField.getText());
			cur.setSex((String)sexComboBox.getSelectedItem());
			try {
				cur.delete();
				fillTable(sortBy, sortAscending);
				clearInvoer();
			} catch (SValidationException e) {
				JOptionPane.showMessageDialog(null,
						e.getMessage(),
						"Validatie", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private class TableSelectionListener implements ListSelectionListener {
	    public void valueChanged(ListSelectionEvent e) {
	        //Ignore extra messages.
	        if (e.getValueIsAdjusting()) return;

	        ListSelectionModel lsm = (ListSelectionModel)e.getSource();
	        if (lsm.isSelectionEmpty()) {
	            //no rows are selected
	        	getInvoerButton().setEnabled(true);
	        	getWijzigButton().setEnabled(false);
	        	getVerwijderButton().setEnabled(false);
	        } else {
	            int selectedRow = lsm.getMinSelectionIndex();
	            //selectedRow is selected
	        	getInvoerButton().setEnabled(false);
	        	getWijzigButton().setEnabled(true);
	        	getVerwijderButton().setEnabled(true);
	        	CategorieBean r = (CategorieBean)olist.get(selectedRow);
	        	getCategorieTextField().setText(r.getCat());
	        	getCategorieTextField().setEnabled(false);
	        	getSexComboBox().setSelectedItem(r.getSex());
	        	getSexComboBox().setEnabled(false);
	    		getVanTextField().setText(r.getVan().toString());
	    		getTemTextField().setText(r.getTem().toString());
	        }
	    }
	}
	
	private class TableSorter extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            TableColumnModel columnModel = jTable.getColumnModel();
            int viewColumn = columnModel.getColumnIndexAtX(e.getX()); 
            int column = jTable.convertColumnIndexToModel(viewColumn); 
            if(e.getClickCount() == 1 && column != -1) {
                sortAscending = new Boolean(!sortAscending.booleanValue());
                sortBy = jTable.getModel().getColumnName(column);
                fillTable(sortBy, sortAscending);
                clearInvoer();
            }
         }
	}

	/**
	 * This is the default constructor
	 */
	public OnderhoudCategorie() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setLayout(new BorderLayout());
		this.setSize(393, 565);
		this.add(getInvoerPanel(), java.awt.BorderLayout.NORTH);
		this.add(getJScrollPane(), java.awt.BorderLayout.CENTER);
		fillTable("cat", new Boolean(true));
	}

	/**
	 * This method initializes invoerjPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getInvoerPanel() {
		if (invoerPanel == null) {
			GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
			gridBagConstraints21.fill = java.awt.GridBagConstraints.NONE;
			gridBagConstraints21.gridy = 3;
			gridBagConstraints21.weightx = 1.0;
			gridBagConstraints21.anchor = java.awt.GridBagConstraints.WEST;
			gridBagConstraints21.insets = new java.awt.Insets(5,5,5,5);
			gridBagConstraints21.ipadx = 20;
			gridBagConstraints21.gridx = 1;
			GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.gridx = 0;
			gridBagConstraints11.insets = new java.awt.Insets(5,5,5,5);
			gridBagConstraints11.anchor = java.awt.GridBagConstraints.EAST;
			gridBagConstraints11.gridy = 3;
			jLabel3 = new JLabel();
			jLabel3.setText("Leeftijd t/m");
			GridBagConstraints gridBagConstraints18 = new GridBagConstraints();
			gridBagConstraints18.gridy = 2;
			gridBagConstraints18.weightx = 1.0;
			gridBagConstraints18.anchor = java.awt.GridBagConstraints.WEST;
			gridBagConstraints18.insets = new java.awt.Insets(5,5,5,5);
			gridBagConstraints18.ipadx = 20;
			gridBagConstraints18.fill = java.awt.GridBagConstraints.VERTICAL;
			gridBagConstraints18.gridx = 1;
			GridBagConstraints gridBagConstraints17 = new GridBagConstraints();
			gridBagConstraints17.gridx = 0;
			gridBagConstraints17.anchor = java.awt.GridBagConstraints.EAST;
			gridBagConstraints17.insets = new java.awt.Insets(5,5,5,5);
			gridBagConstraints17.gridy = 2;
			jLabel2 = new JLabel();
			jLabel2.setText("Leeftijd van");
			GridBagConstraints gridBagConstraints16 = new GridBagConstraints();
			gridBagConstraints16.gridy = 1;
			gridBagConstraints16.weightx = 1.0;
			gridBagConstraints16.insets = new java.awt.Insets(5,5,5,5);
			gridBagConstraints16.ipadx = 20;
			gridBagConstraints16.anchor = java.awt.GridBagConstraints.WEST;
			gridBagConstraints16.gridx = 1;
			GridBagConstraints gridBagConstraints15 = new GridBagConstraints();
			gridBagConstraints15.gridx = 0;
			gridBagConstraints15.anchor = java.awt.GridBagConstraints.EAST;
			gridBagConstraints15.insets = new java.awt.Insets(5,5,5,5);
			gridBagConstraints15.gridy = 1;
			jLabel1 = new JLabel();
			jLabel1.setText("Sex");
			GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
			gridBagConstraints6.gridy = 0;
			gridBagConstraints6.weightx = 1.0;
			gridBagConstraints6.ipadx = 150;
			gridBagConstraints6.anchor = java.awt.GridBagConstraints.WEST;
			gridBagConstraints6.fill = java.awt.GridBagConstraints.VERTICAL;
			gridBagConstraints6.insets = new java.awt.Insets(5,5,5,5);
			gridBagConstraints6.gridx = 1;
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.gridx = 0;
			gridBagConstraints5.insets = new java.awt.Insets(5,5,5,5);
			gridBagConstraints5.anchor = java.awt.GridBagConstraints.EAST;
			gridBagConstraints5.gridy = 0;
			jLabel = new JLabel();
			jLabel.setText("Categorie");
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.fill = GridBagConstraints.BOTH;
			gridBagConstraints3.gridx = 2;
			gridBagConstraints3.gridy = 3;
			gridBagConstraints3.insets = new Insets(3, 3, 3, 3);
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.insets = new Insets(3, 3, 3, 3);
			gridBagConstraints2.gridy = 2;
			gridBagConstraints2.gridx = 2;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.fill = GridBagConstraints.BOTH;
			gridBagConstraints.gridx = 2;
			gridBagConstraints.gridy = 0;
			gridBagConstraints.insets = new Insets(3, 3, 3, 3);
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.fill = GridBagConstraints.BOTH;
			gridBagConstraints1.gridx = 2;
			gridBagConstraints1.gridy = 1;
			gridBagConstraints1.insets = new Insets(3, 3, 3, 3);
			invoerPanel = new JPanel();
			invoerPanel.setLayout(new GridBagLayout());
			invoerPanel.add(getWijzigButton(), gridBagConstraints1);
			invoerPanel.add(getInvoerButton(), gridBagConstraints);
			invoerPanel.add(getVerwijderButton(), gridBagConstraints2);
			invoerPanel.add(getHerstelButton(), gridBagConstraints3);
			invoerPanel.add(jLabel, gridBagConstraints5);
			invoerPanel.add(getCategorieTextField(), gridBagConstraints6);
			invoerPanel.add(jLabel1, gridBagConstraints15);
			invoerPanel.add(getSexComboBox(), gridBagConstraints16);
			invoerPanel.add(jLabel2, gridBagConstraints17);
			invoerPanel.add(getVanTextField(), gridBagConstraints18);
			invoerPanel.add(jLabel3, gridBagConstraints11);
			invoerPanel.add(getTemTextField(), gridBagConstraints21);
		}
		return invoerPanel;
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJTable());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jTable	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTable() {
		if (jTable == null) {
			jTable = new JTable();
			jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
			jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			jTable.setShowGrid(true);
// Ask to be notified of selection changes.
			jTable.getSelectionModel().addListSelectionListener(new TableSelectionListener());
// Make column header click result in sorting ascending (shift-click is descending)
			jTable.setColumnSelectionAllowed(false);
	        TableSorter listSorter = new TableSorter();
			JTableHeader th = jTable.getTableHeader();
	        th.addMouseListener(listSorter); 
		}
		return jTable;
	}

	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getInvoerButton() {
		if (invoerButton == null) {
			invoerButton = new JButton();
			invoerButton.setText("Voer in");
			invoerButton.addActionListener(new InvoerButtonActionListener());
		}
		return invoerButton;
	}

	/**
	 * This method initializes herstelButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getHerstelButton() {
		if (herstelButton == null) {
			herstelButton = new JButton();
			herstelButton.setText("Herstel");
			herstelButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					fillTable(sortBy, sortAscending);
					clearInvoer();
				}
			});
		}
		return herstelButton;
	}

	/**
	 * This method initializes jButton1	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getWijzigButton() {
		if (wijzigButton == null) {
			wijzigButton = new JButton();
			wijzigButton.setText("Wijzig");
			wijzigButton.setEnabled(false);
			wijzigButton.addActionListener(new WijzigButtonActionListener());
		}
		return wijzigButton;
	}

	/**
	 * This method initializes jButton2	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getVerwijderButton() {
		if (verwijderButton == null) {
			verwijderButton = new JButton();
			verwijderButton.setText("Verwijder");
			verwijderButton.setEnabled(false);
			verwijderButton.addActionListener(new VerwijderButtonActionListener());
		}
		return verwijderButton;
	}

	/*
	 * ========================================================================
	 */
	@SuppressWarnings("unchecked")
	private void fillTable(String sortBy, Boolean ascending) {
		List<CategorieBean> tmp = new ArrayList<CategorieBean>();
		/// Prepare and execute the query
		boolean hasBegun = SConnection.getConnection().hasBegun();
		if( ! hasBegun ) { SConnection.begin(); }
		SPreparedStatement stmt = Categorie.meta.select(
				"1=1", sortBy+(ascending.booleanValue()?"":" DESC"));
		SResultSet res = stmt.execute();
		
		/// loop through the results
		while (res.hasNext()) {
			CategorieBean strt = new CategorieBean(((Categorie)res.getRecord()));
			tmp.add(strt);
		}
		if( ! hasBegun ) { SConnection.commit(); }
    	olist = CollectionUtilities.observableList(tmp);
		TableUtilities.setViewToModel("LangebaanModel.xml", "Categorie", getJTable(), olist);
		TableColumn col1 = getJTable().getColumnModel().getColumn(0);
		col1.setMaxWidth(150);
		TableColumn col2 = getJTable().getColumnModel().getColumn(1);
		col2.setMaxWidth(30);
		TableColumn col3 = getJTable().getColumnModel().getColumn(2);
		col3.setMaxWidth(70);
		TableColumn col4 = getJTable().getColumnModel().getColumn(3);
		col4.setMaxWidth(70);
	}
	
	private void clearInvoer() {
		getCategorieTextField().setText(null);
		getCategorieTextField().setEnabled(true);
		getSexComboBox().setSelectedIndex(0);
		getSexComboBox().setEnabled(true);
		getVanTextField().setText(null);
		getTemTextField().setText(null);
	}

	/**
	 * This method initializes jTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getCategorieTextField() {
		if (categorieTextField == null) {
			categorieTextField = new JTextField();
		}
		return categorieTextField;
	}

	/**
	 * This method initializes sexComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getSexComboBox() {
		if (sexComboBox == null) {
			sexComboBox = new JComboBox();
			sexComboBox.addItem("H");
			sexComboBox.addItem("D");
			sexComboBox.addItem("A");
		}
		return sexComboBox;
	}

	/**
	 * This method initializes leeftijdTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getVanTextField() {
		if (vanTextField == null) {
			vanTextField = new JTextField();
		}
		return vanTextField;
	}

	/**
	 * This method initializes temTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTemTextField() {
		if (temTextField == null) {
			temTextField = new JTextField();
		}
		return temTextField;
	}


}  //  @jve:decl-index=0:visual-constraint="10,10"
